﻿#include "QlyAVCodecContext.h"
#include "QlyAVPacket.h"

QlyAVPacket::QlyAVPacket()
{
    pPacket = av_packet_alloc();
}

QlyAVPacket::~QlyAVPacket()
{
    //av_packet_unref(pPacket);
    av_packet_free(&pPacket);
}

QlyAVPacket::QlyAVPacket(const QlyAVPacket &source)
{
    if(pPacket != nullptr)
    {
        //av_packet_unref(pPacket);
        av_packet_free(&pPacket);
    }
    pPacket = av_packet_clone(source.pPacket);
}

QlyAVPacket & QlyAVPacket::operator= (const QlyAVPacket & source)
{
    if(pPacket != nullptr)
    {
        av_packet_free(&pPacket);
    }
    pPacket = av_packet_clone(source.pPacket);
    return *this;
}

void QlyAVPacket::reset()
{
    av_packet_unref(pPacket);
}

int QlyAVPacket::compare_ts(double timestamp)
{
    AVRational av_time_base_q = {1, AV_TIME_BASE};
    return av_compare_ts(pPacket->pts, m_timeBase, timestamp * AV_TIME_BASE, av_time_base_q);
}

void QlyAVPacket::adjustTime(double timestamp)
{
    int64_t ts = timestamp * m_timeBase.den / m_timeBase.num;
    pPacket->pts = pPacket->pts - ts;
    pPacket->dts = pPacket->dts - ts;
}

void QlyAVPacket::changeTimeBase(AVRational bq, AVRational cq, enum AVRounding rnd)
{
    pPacket->pts = av_rescale_q_rnd(pPacket->pts, bq, cq, rnd);
    pPacket->dts = av_rescale_q_rnd(pPacket->dts, bq, cq, rnd);
    pPacket->duration = av_rescale_q(pPacket->duration, bq, cq);
    pPacket->pos = -1;
}

void QlyAVPacket::setStreamIndex(unsigned int index)
{
    pPacket->stream_index = index;
}
